
#include <QtGui>
#include <QtOpenGL\QtOpenGL>
#include <QtOpenGL\QGLWidget>
#include <QStackedLayout>

#include <vector>
using namespace std;
//sample
#include "GLWidget.h"

#include "Data.h"
#include "Spreadsheet.h"
#include "FindDialog.h"

#include "mainwindow.h"

#include "Gfx.h"
#include "CalibrationData.h"
#include "RoomData.h"
#include "Helper.h"
#include "FileIO.h"


class CGfx;
class CRoadGfx;
class CRoomGfx;
class CCalibrationGfx;
class CRoadData;
class CRoomData;
class CNoiseData;
class CCalibrationData;


//QStringList CMainWindow::_slRecentProjects;

CMainWindow::CMainWindow()
{
    // define a tree widget showing the organization of files
    _pTreeWidget = new QTreeWidget(this);
    //_pTreeWidget->setColumnCount(2);
    _pTreeWidget->setHeaderHidden(true);
    _pTreeWidget->setIconSize(QSize(30,30));
    _pTreeWidget->show();
    connect(_pTreeWidget,SIGNAL(itemClicked(QTreeWidgetItem*, int )),this,SLOT(setActiveSubWindow(QTreeWidgetItem*)));
    connect(_pTreeWidget,SIGNAL(itemClicked(QTreeWidgetItem*, int )),this,SLOT(switchProject(QTreeWidgetItem*)));
    connect(_pTreeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int )),this,SLOT(setMaximizeSubWindow(QTreeWidgetItem*)));
    // initialize a dock widget to hold the tree
    _pDockWidget = new QDockWidget(tr("files"),this);
    _pDockWidget->setObjectName("pDockWidget");
    _pDockWidget->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
    _pDockWidget->setWidget(_pTreeWidget);
    addDockWidget(Qt::LeftDockWidgetArea,_pDockWidget);

    // define graphical widget and MDI widget
    _pData = new CData;
    _pGlWidget = new GLWidget(NULL/*,_pData*/); 
    _pMDIArea = new QMdiArea(this); // Multi Document Interface
    connect(_pMDIArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),this, SLOT(updateActions()));
    connect(_pMDIArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),this, SLOT(updateTreeDock(QMdiSubWindow*)));
    connect(_pMDIArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),this, SLOT(setStatusBar(QMdiSubWindow*)));

    _pWindowMapper = new QSignalMapper(this);// map the sub-window actions in the windows menu with the activation of sub-windows
    connect(_pWindowMapper, SIGNAL(mapped(QWidget *)),this, SLOT(setActiveSubWindow(QWidget *)));
    
    // initialize a central layout to hold graphics and MDI widget
    _pCentralLayout = new QStackedLayout(this);
    _pCentralLayout->addWidget(_pGlWidget);
    _pCentralLayout->addWidget(_pMDIArea);
    _pCentralLayout->setSpacing(0);
    _pCentralLayout->setMargin(0);

    _pFindDialog = NULL;

    // initialize a central widget to hold central layout
    QWidget* pCentralWidget = new QWidget(this);
    pCentralWidget->setLayout(_pCentralLayout);
    setCentralWidget(pCentralWidget);

    createActions();
    createMenus();
    createToolBars();
    createStatusBar();
    updateActions();

    _bFullscreen = false;
    _bShowGraphics = false;

    readSettings(); //recover window settings
    showFullScreen(_bFullscreen);
    showGraphics(_bShowGraphics);

    //setWindowIcon(QIcon(":/images/project_whole.png"));

    setWindowTitle(tr("VPAL"));
    _nTimerID = startTimer(30);
    //if(!_sCurPathProjectExt.isEmpty()) loadProject(_sCurPathProjectExt);
    for ( int i =0 ;i < _slRecentProjects.count();i++)
    {
        loadProject(_slRecentProjects[i]);
    }

    InitRand(); 
}

CMainWindow::~CMainWindow()
{
    //if(_pData) 
    //    delete _pData;

    if(_pDockWidget)
        delete _pDockWidget;
    delete _pGlWidget;
    delete _pData;
}

void CMainWindow::about()
 {
     QMessageBox::about(this, tr("About Grabber"),
             tr("The software is used to organize vision test. "
                " Vision and Perception Group."));
 }

void CMainWindow::createActions()
{
    // File
/*
    _pNewAct = new QAction(tr("&New"), this);
    _pNewAct->setIcon(QIcon(":/images/new.png"));
    _pNewAct->setShortcut(QKeySequence::New);
    _pNewAct->setStatusTip(tr("Create a new spreadsheet file"));
    connect(_pNewAct, SIGNAL(triggered()), this, SLOT(newFile()));*/


    _pOpenAct = new QAction(tr("&Open"), this);
    _pOpenAct->setIcon(QIcon(":/images/open.png"));
    _pOpenAct->setShortcut(QKeySequence::Open);
    _pOpenAct->setStatusTip(tr("Open an exist spreadsheet file"));
    connect(_pOpenAct, SIGNAL(triggered()), this, SLOT(openProjectFile()));

    _pAddFilesAct= new QAction(tr("Add &Files"), this);
    //_pOpenFileAct->setIcon(QIcon(":/images/open.png"));
    _pAddFilesAct->setShortcut(tr("Ctrl+A"));
    _pAddFilesAct->setStatusTip(tr("Open an exist spreadsheet file"));
    connect(_pAddFilesAct, SIGNAL(triggered()), this, SLOT(open()));

    _pSaveAct = new QAction(tr("&Save"), this);
    _pSaveAct->setIcon(QIcon(":/images/save.png"));
    _pSaveAct->setShortcut(QKeySequence::Save);
    _pSaveAct->setStatusTip(tr("Save the current file"));
    connect(_pSaveAct, SIGNAL(triggered()), this, SLOT(save()));

    _pSaveAsAct = new QAction(tr("Save As"), this);
    connect(_pSaveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));

    _pSaveAllAct = new QAction(tr("&Save All"), this);
    _pSaveAllAct->setIcon(QIcon(":/images/save_all.png"));
    _pSaveAllAct->setStatusTip(tr("Save all files"));
    connect(_pSaveAllAct, SIGNAL(triggered()), this, SLOT(saveAll()));

    for (int i = 0; i < MaxRecentFiles; ++i) {
        _aRecentFileActions[i] = new QAction(this);
        _aRecentFileActions[i]->setVisible(false);
        connect(_aRecentFileActions[i], SIGNAL(triggered()),this, SLOT(openRecentProject()));
    }

    _pExitAct = new QAction(tr("E&xit"), this);
    _pExitAct->setShortcut(tr("Ctrl+Q"));
    connect(_pExitAct, SIGNAL(triggered()), this, SLOT(close()));

    // Edit
    _pCutAct = new QAction(tr("Cu&t"), this);
    _pCutAct->setIcon(QIcon(":/images/cut.png"));
    _pCutAct->setShortcut(QKeySequence::Cut);
    _pCutAct->setStatusTip(tr("Cut the cells"));
    connect(_pCutAct, SIGNAL(triggered()),  this, SLOT(cut()));

    _pCopyAct = new QAction(tr("&Copy"), this);
    _pCopyAct->setIcon(QIcon(":/images/copy.png"));
    _pCopyAct->setShortcut(QKeySequence::Copy);
    _pCopyAct->setStatusTip(tr("Copy the cells"));
    connect(_pCopyAct, SIGNAL(triggered()),  this, SLOT(copy()));

    _pPasteAct = new QAction(tr("&Paste"), this);
    _pPasteAct->setIcon(QIcon(":/images/paste.png"));
    _pPasteAct->setShortcut(QKeySequence::Paste);
    _pPasteAct->setStatusTip(tr("Paste the cells"));
    connect(_pPasteAct, SIGNAL(triggered()),  this, SLOT(paste()));

    _pDeleteAct = new QAction(tr("&Delete"), this);
    _pDeleteAct->setIcon(QIcon(":/images/delete.png"));
    _pDeleteAct->setShortcut(QKeySequence::Delete);
    _pDeleteAct->setStatusTip(tr("Delete the cells"));
    connect(_pDeleteAct, SIGNAL(triggered()),  this, SLOT(del()));

    _pInsertAct = new QAction(tr("&Insert"), this);
    _pInsertAct->setIcon(QIcon(":/images/delete.png"));
    //_pInsertAct->setShortcut(QKeySequence::Insert);
    _pInsertAct->setStatusTip(tr("Delete the cells"));
    connect(_pInsertAct, SIGNAL(triggered()),  this, SLOT(insertRowAboveCurrent()));

    _pSelectRowAct = new QAction(tr("&Row"), this);
    _pSelectRowAct->setStatusTip(tr("Select one row of the cells in the spreadsheet"));
    connect(_pSelectRowAct, SIGNAL(triggered()), this, SLOT(selectCurrentRow()));

    _pSelectColumnAct = new QAction(tr("&Column"), this);
    _pSelectColumnAct->setStatusTip(tr("Select one column of the cells in the spreadsheet"));
    connect(_pSelectColumnAct, SIGNAL(triggered()), this, SLOT(selectCurrentColumn()));

    _pSelectAllAct = new QAction(tr("&All"), this);
    _pSelectAllAct->setShortcut(QKeySequence::SelectAll);
    _pSelectAllAct->setStatusTip(tr("Select all the cells in the spreadsheet"));
    connect(_pSelectAllAct, SIGNAL(triggered()), this, SLOT(selectAll()));

    _pFindAct = new QAction(tr("&Find"), this);
    _pFindAct->setIcon(QIcon(":/images/find.png"));
    _pFindAct->setShortcut(QKeySequence::Find);
    _pFindAct->setStatusTip(tr("find"));
    connect(_pFindAct, SIGNAL(triggered()),this, SLOT(find()));

    _pGotoCellAct = new QAction(tr("&Go to Cell"), this);
    _pGotoCellAct->setIcon(QIcon(":/images/gotocell.jpeg"));
    _pGotoCellAct->setShortcut(tr("Ctrl+G"));
    _pGotoCellAct->setStatusTip(tr("Go to cell"));
    connect(_pGotoCellAct, SIGNAL(triggered()), this, SLOT(goToCell()));

    _pSortAct = new QAction(tr("&Sort"), this);
    _pSortAct->setIcon(QIcon(":/images/sort.png"));
    _pSortAct->setShortcut(tr("Ctrl+G"));
    _pSortAct->setStatusTip(tr("Sort the column."));
    connect(_pSortAct, SIGNAL(triggered()), this, SLOT(sort()));

    // View
    _pShowGfxAct = new QAction(tr("Graphics"),this);
    //_pShowGfxAct->setShortcut(tr("F11"));
    _pShowGfxAct->setCheckable(true);
    _pShowGfxAct->setChecked(_bShowGraphics);
    connect(_pShowGfxAct, SIGNAL(toggled(bool)),           this,        SLOT(showGraphics(bool)));
    connect(_pShowGfxAct, SIGNAL(toggled(bool)),           this,        SLOT(setDisplayMode(bool)));
    connect(this,         SIGNAL(displayModeChanged(bool)),_pShowGfxAct,SLOT(setChecked(bool)));
    connect(this,         SIGNAL(displayModeChanged(bool)),_pShowGfxAct,SLOT(setDisplayMode(bool)));

    _pFullScreenAct = new QAction(tr("Fullscreen"),this);
    _pFullScreenAct->setShortcut(tr("F12"));
    _pFullScreenAct->setCheckable(true);
    _pFullScreenAct->setChecked(_bFullscreen);
    connect(_pFullScreenAct, SIGNAL(toggled(bool)),          this,           SLOT(showFullScreen(bool)));
    connect(_pFullScreenAct, SIGNAL(toggled(bool)),          this,           SLOT(setFullScreen(bool)));
    connect(this,            SIGNAL(fullScreenChanged(bool)),_pFullScreenAct,SLOT(setChecked(bool)));

    _pRunAct = new QAction(tr("&Run"),this);
    //_pRunAct->setShortcut(tr("F5"));
    _pRunAct->setStatusTip(tr("Run the experiment."));
    _pRunAct->setIcon(QIcon(":/images/play.png"));
    connect(_pRunAct, SIGNAL(triggered()),this,SLOT(runExperiment()));

    _pNextTrialAct = new QAction(tr("&Next"),this);
    _pNextTrialAct->setShortcut(tr("Key_PageDown"));
    _pNextTrialAct->setStatusTip(tr("Next trial."));
    _pNextTrialAct->setIcon(QIcon(":/images/next.png"));
    connect(_pNextTrialAct, SIGNAL(triggered()),this,SLOT(nextTrial()));

    _pStopExperimentAct = new QAction(tr("&Stop"),this);
    _pStopExperimentAct->setShortcut(tr("Key_Escape"));
    _pStopExperimentAct->setStatusTip(tr("Stop experiment."));
    _pStopExperimentAct->setIcon(QIcon(":/images/stop.png"));
    connect(_pStopExperimentAct, SIGNAL(triggered()),this,SLOT(exitAllTrial()));

    _pCalibration = new QAction(tr("&Calibration"),this);
    _pCalibration->setShortcut(tr("F4"));
    _pCalibration->setStatusTip(tr("Calibration."));
    connect(_pCalibration, SIGNAL(triggered()),this,SLOT(calibration()));

    _pExportAct = new QAction(tr("&Export"),this);
    _pExportAct->setStatusTip(tr("Run the experiment."));
    _pExportAct->setIcon(QIcon(":/images/export.png"));
    connect(_pExportAct, SIGNAL(triggered()),this,SLOT(exportData()));

    // Window
    _pCloseAct = new QAction(tr("&Close"), this);
    _pCloseAct->setShortcut(QKeySequence::Close);
    _pCloseAct->setStatusTip(tr("Close this window"));
    connect(_pCloseAct, SIGNAL(triggered()), this, SLOT(close()));

    _pCloseAllAct = new QAction(tr("Close &All"),this);
    connect(_pCloseAllAct,SIGNAL(triggered()),this,SLOT(closeAll()));

    _pTileAct = new QAction(tr("&Tile"),this);
    _pTileAct->setStatusTip(tr("Tile the windows"));
    connect(_pTileAct,SIGNAL(triggered()), _pMDIArea, SLOT(tileSubWindows()));

    _pCascadeAct = new QAction(tr("&Cascade"),this);
    _pCascadeAct->setStatusTip(tr("Cascade the windows"));
    connect(_pCascadeAct,SIGNAL(triggered()),_pMDIArea,SLOT(cascadeSubWindows()));

    _pNextAct = new QAction(tr("Ne&xt"), this);
    _pNextAct->setShortcuts(QKeySequence::NextChild);
    _pNextAct->setStatusTip(tr("Move the focus to the next window"));
    connect(_pNextAct, SIGNAL(triggered()),_pMDIArea, SLOT(activateNextSubWindow()));

    _pPreviousAct = new QAction(tr("Pre&vious"), this);
    _pPreviousAct->setShortcuts(QKeySequence::PreviousChild);
    _pPreviousAct->setStatusTip(tr("Move the focus to the previous window"));
    connect(_pPreviousAct, SIGNAL(triggered()),_pMDIArea, SLOT(activatePreviousSubWindow()));

    _pSeparatorAct2 = new QAction(this);
    _pSeparatorAct2->setSeparator(true);

    // About
    _pAboutAct = new QAction(tr("&About"), this);
    connect(_pAboutAct, SIGNAL(triggered()), this, SLOT(about()));

    _pAboutQtAct = new QAction(tr("About &Qt"), this);
    connect(_pAboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}

void CMainWindow::createToolBars()
{
    _pFileToolBar = addToolBar(tr("&File"));
    /*_pFileToolBar->addAction(_pNewAct);*/
    _pFileToolBar->addAction(_pOpenAct);
    _pFileToolBar->addAction(_pSaveAct);
    _pFileToolBar->addAction(_pSaveAllAct);
    _pFileToolBar->addAction(_pExportAct);

    //_pFileToolBar->setIconSize(QSize(50,50));

    _pEditToolBar = addToolBar(tr("&Edit"));
    _pEditToolBar->addAction(_pCutAct);
    _pEditToolBar->addAction(_pCopyAct);
    _pEditToolBar->addAction(_pPasteAct);
    _pEditToolBar->addSeparator();
    _pEditToolBar->addAction(_pFindAct);
    _pEditToolBar->addAction(_pSortAct);
    //_pEditToolBar->addAction(_pGotoCellAct);
    //_pEditToolBar->setIconSize(QSize(50,50));
    _pSystemBar = addToolBar(tr("&System"));
    _pSystemBar->addAction(_pRunAct);
    _pSystemBar->addAction(_pNextTrialAct);
    _pSystemBar->addAction(_pStopExperimentAct);

    _pOtherToolBar = addToolBar(tr("&Other"));
    _pOtherToolBar->addAction(_pCalibration);

}
void CMainWindow::createMenus()
{
    // Window
    _pFileMenu = menuBar()->addMenu(tr("&File"));
    _pFileMenu->addAction(_pOpenAct);
    _pFileMenu->addAction(_pAddFilesAct);
    _pFileMenu->addAction(_pSaveAct);
    _pFileMenu->addAction(_pSaveAsAct);
    _pFileMenu->addAction(_pSaveAllAct);
    _pFileMenu->addAction(_pExportAct);
    _pSeparatorAct1 = _pFileMenu->addSeparator(); //This will allow us to hide the separator (if there are no recent files)
    for( int i=0; i < MaxRecentFiles; ++i ) _pFileMenu->addAction(_aRecentFileActions[i]);
    _pFileMenu->addSeparator();
    _pFileMenu->addAction(_pExitAct);

    // Edit
    _pEditMenu = menuBar()->addMenu(tr("&Edit"));
    _pEditMenu->addAction(_pCutAct);
    _pEditMenu->addAction(_pCopyAct);
    _pEditMenu->addAction(_pPasteAct);
    _pEditMenu->addAction(_pDeleteAct);
    _pEditMenu->addAction(_pInsertAct);
    _pSelectSubMenu = _pEditMenu->addMenu(tr("&Select"));
    _pSelectSubMenu->addAction(_pSelectRowAct);
    _pSelectSubMenu->addAction(_pSelectColumnAct);
    _pSelectSubMenu->addAction(_pSelectAllAct);
    _pEditMenu->addSeparator();
    _pEditMenu->addAction(_pFindAct);
    _pEditMenu->addAction(_pSortAct);
    //_pEditMenu->addAction(_pGotoCellAct);

    // View
    _pViewMenu = menuBar()->addMenu(tr("&View"));
    _pViewMenu->addAction(_pFullScreenAct);
    _pViewMenu->addAction(_pShowGfxAct);
    _pViewMenu->addAction(_pRunAct);
    _pViewMenu->addAction(_pNextTrialAct);
    _pViewMenu->addAction(_pStopExperimentAct);

    // Other
    _pOtherMenu = menuBar()->addMenu(tr("&Other"));
    _pOtherMenu->addAction(_pCalibration);

    // Windows
    _pWindowMenu = menuBar()->addMenu(tr("&Window"));
    updateWindowMenu();
    connect(_pWindowMenu, SIGNAL(aboutToShow()), this, SLOT(updateWindowMenu()));
    
    menuBar()->addSeparator();
    // About
    _pHelpMenu = menuBar()->addMenu(tr("&Help"));
    _pHelpMenu->addAction(_pAboutAct);
    _pHelpMenu->addAction(_pAboutQtAct);

}

// Setting Up the Status Bar
void CMainWindow::createStatusBar()
{
    _pLocationLabel = new QLabel("      ",this);
    _pLocationLabel->setAlignment(Qt::AlignHCenter);
    _pLocationLabel->setMinimumSize(_pLocationLabel->sizeHint());

    _pFormulaLabel = new QLabel;
    _pFormulaLabel->setIndent(3);

    statusBar()->addWidget(_pLocationLabel);
    statusBar()->addWidget(_pFormulaLabel, 1);


}
void CMainWindow::keyPressEvent( QKeyEvent *e_ )
{
    switch ( e_->key() )
    {
        case Qt::Key_F12:
            setFullScreen(!_bFullscreen);
            break;
        case Qt::Key_F11:
            setDisplayMode(!_bShowGraphics);
            exitAllTrial();
            break;
		case Qt::Key_F10:
			if(_pGlWidget->_pGfx->exptState()==CGfx::NormalView)
				_pGlWidget->_pGfx->setExptState()=CGfx::BirdView;
			else if(_pGlWidget->_pGfx->exptState()==CGfx::BirdView)
				_pGlWidget->_pGfx->setExptState()=CGfx::NormalView;
			break;
        case Qt::Key_F1:
            if(_pGlWidget->_pGfx->exptState()==CGfx::NormalView)
                _pGlWidget->_pGfx->setShowScene()=!_pGlWidget->_pGfx->showScene();
            break;
        case Qt::Key_Escape:
            exitAllTrial();
            break;

        case Qt::Key_PageDown:
            nextTrial();
            break;
        case Qt::Key_Left:
            if(_pData&&_pGlWidget)
                _pData->setXPosition() += 0.01;
            break;
        case Qt::Key_Right:
            if(_pData&&_pGlWidget)
                _pData->setXPosition() -= 0.01;
            break;
        case Qt::Key_F5:
            runExperiment();
            break;
        case Qt::Key_Delete:
            break;
    }
    if(e_->modifiers() == Qt::Key_Shift)
    {
        if(activeSpreadsheet())
            activeSpreadsheet()->removeCurrentRow();
    }
}

bool CMainWindow::save()
{
    if (activeSpreadsheet() && activeSpreadsheet()->save())
        statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

bool CMainWindow::saveAs()
{
    //QString sFileName = QFileDialog::getSaveFileName(this,
    //    tr("Save Spreadsheet"), ".",
    //    tr("Spreadsheet files (*.sp)\n"
    //    "Comma-separated values files (*.csv)\n"
    //    "Lotus 1-2-3 files (*.wk1 *.wks)")); // additional argument: QFileDialog::DontConfirmOverwrite
    //if (sFileName.isEmpty())
    //    return false;
    //return saveFile(sFileName);

    if (activeSpreadsheet() && activeSpreadsheet()->saveAs())
        statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

bool CMainWindow::saveAll()
{
    // close and save all sub-windows
    QList<QMdiSubWindow *> lWindows = _pMDIArea->subWindowList();
    for (int i = 0; i < lWindows.size(); ++i) {
        CSpreadsheet *pSpreadsheet = qobject_cast<CSpreadsheet *>(lWindows.at(i)->widget());
        pSpreadsheet->save();
    }
    return true;
}

bool CMainWindow::showGraphics(bool bShow_)
{
    if(bShow_)
    {
        _pCentralLayout->setCurrentIndex(0);

        _pFileToolBar->hide();
        _pEditToolBar->hide();
        _pDockWidget->hide();

        statusBar()->hide();
        if(_bFullscreen)
        {
            _pSystemBar->hide();
            _pOtherToolBar->hide();

            setCursor(Qt::BlankCursor);
        }
        else 
        {
            _pSystemBar->show();
            _pOtherToolBar->show();
            setCursor(Qt::ArrowCursor);
        }
        /*_pNewAct->setVisible(false);*/
        /*_pNewAct->setDisabled(true);*/
        _pOpenAct->setVisible(false);
        _pOpenAct->setDisabled(true);
        _pSaveAct->setVisible(false);
        _pSaveAct->setDisabled(true);
        _pSaveAsAct->setVisible(false);
        _pSaveAsAct->setDisabled(true);

        _pEditMenu->setDisabled(true);
    }
    else
    {
        setCursor(Qt::ArrowCursor);
        _pCentralLayout->setCurrentIndex(1);

        _pFileToolBar->show();
        _pEditToolBar->show();
        _pOtherToolBar->show();
        _pSystemBar->show();
        _pDockWidget->show();
        statusBar()->show();
       
        _pOpenAct->setVisible(true);
        _pOpenAct->setEnabled(true);
        _pSaveAct->setVisible(true);
        _pSaveAsAct->setVisible(true);

        _pEditMenu->setEnabled(true);
    }
    return true;
}

void CMainWindow::showFullScreen(bool bFullScreen_)
{
    if(bFullScreen_)
    {
        writeSettings();
        menuBar()->hide();
        _pSystemBar->hide();
        _pFileToolBar->hide();
        _pEditToolBar->hide();
        _pOtherToolBar->hide();
        setWindowState(windowState()^Qt::WindowFullScreen);
    }
    else
    {
        readSettings();
        Qt::WindowFlags flags = 0;
        flags = Qt::Window;
        flags |= Qt::WindowTitleHint;
        flags |= Qt::WindowMinimizeButtonHint;
        flags |= Qt::WindowMaximizeButtonHint;
        setWindowFlags(flags);
        menuBar()->show();
        _pSystemBar->show();
        _pOtherToolBar->show();
        _pFileToolBar->show();
        _pEditToolBar->show();
        show();
    }
}

void CMainWindow::updateSubWindows(QStringList& lPathFileNameExts_)
{
    QMutableStringListIterator i(lPathFileNameExts_);
    while (i.hasNext()) {
        QString sPapthFileNameExt = i.next();
        QString sFileName = QFileInfo(sPapthFileNameExt).fileName();
        QList<QMdiSubWindow *> lWindows = _pMDIArea->subWindowList();
        for (int i = 0; i < lWindows.size(); ++i) {
            CSpreadsheet *pSpreadsheet = qobject_cast<CSpreadsheet *>(lWindows.at(i)->widget());
            if(pSpreadsheet->getCurrentFile().contains(sFileName))
            {
                _pMDIArea->setActiveSubWindow(lWindows.at(i));
                _pMDIArea->closeActiveSubWindow();
            }
        }
    }
}

void CMainWindow::createFiles(QStringList& lPathFileNameExts_)
{
    QMutableStringListIterator i(lPathFileNameExts_);
    while (i.hasNext()) {
        CSpreadsheet* pSpreadsheet = new CSpreadsheet(this);
        QString sPapthFileNameExt = i.next();
        // if the file is ".prj", then initialize its content 
        if(sPapthFileNameExt.contains(".prj"))
        {
            pSpreadsheet->initPrjContent(lPathFileNameExts_);
        }
        pSpreadsheet->createFile(sPapthFileNameExt);
        addSpreadsheet(pSpreadsheet);
    }
    // title sub windows
    _pMDIArea->tileSubWindows();
}

//bool CMainWindow::updateProjectList(QStringList& lPathFileNameExts_)
//{
//    // check whether the project has been opened
//    for(int i=0;i<_llPathFileExts.length();i++)
//        if(_llPathFileExts.at(i).at(0).contains(lPathFileNameExts_.at(0))) 
//        {
//            QMessageBox::information(this, tr("Warning"), tr("the Project has been opened already"));
//            return false;
//        }
//        // append the new project to the project list
//        _llPathFileExts.append(lPathFileNameExts_);
//        return true;
//}
bool CMainWindow::isProjectOpened(const QString& sPathProjectNameExt_)
{
    for(int i=0;i<_pTreeWidget->topLevelItemCount();i++)
    {
        //check roots
        QTreeWidgetItem* pTree = _pTreeWidget->topLevelItem(i);
        if(pTree->data(1,0).toString().contains(sPathProjectNameExt_)) return true;
        //check leaves
        /*if(pTree->childCount())
        {
            for(int i=0;i<pTree->childCount();i++)
            {
                QTreeWidgetItem* pChild = pTree->child(i);
                if(pChild->text(0).contains(sPathProjectNameExt_)) return true;
            }
        }*/
    }
    return false;
}
void CMainWindow::updateTreeDock(QMdiSubWindow* pSubWindow_)
{
    if(!pSubWindow_) return;
    CSpreadsheet *pSpreadsheet = qobject_cast<CSpreadsheet *>(pSubWindow_->widget());

    for(int i=0;i<_pTreeWidget->topLevelItemCount();i++)
    {
        // check root
        QTreeWidgetItem* pTree = _pTreeWidget->topLevelItem(i);
        if(pTree->data(1,0).toString()==pSpreadsheet->getCurrentFile())
        {
            QFont cFont = pTree->font(0); cFont.setBold(true);
            pTree->setFont(0,cFont);
        }
        else
        {
            QFont cFont = pTree->font(0); cFont.setBold(false);
            pTree->setFont(0,cFont);
        }
        // check children
        for(int j=0;j<pTree->childCount();j++)
        {
            QTreeWidgetItem* pChild = pTree->child(j);
            if(pChild->data(1,0).toString()==pSpreadsheet->getCurrentFile()) 
            {
                QFont cFont = pTree->font(0); cFont.setBold(true);
                pChild->setFont(0,cFont);
            }
            else
            {
                QFont cFont = pTree->font(0); cFont.setBold(false);
                pChild->setFont(0,cFont);
            }
        }
    }
}
void CMainWindow::addNewFileToCurrentProject(const QString& sPathFileNameExt_)
{
    QTreeWidgetItem* pTree = NULL;
    QTreeWidgetItem* pLeaf = NULL;
    QStringList lTemp;lTemp.append(QFileInfo(sPathFileNameExt_).fileName());lTemp.append(sPathFileNameExt_);
    for(int i=0;i<_pTreeWidget->topLevelItemCount();i++)
    {
        // check root
        pTree = _pTreeWidget->topLevelItem(i);
        if(pTree->data(1,0).toString()==_sCurPathProjectExt)
        {
            if(sPathFileNameExt_.contains(".init",Qt::CaseInsensitive))
            {
                if(pTree)
                {
                    pLeaf = new QTreeWidgetItem(pTree, lTemp);
                    pLeaf->setIcon(0,QIcon(":/images/init.png"));
                }
            }
            else if(sPathFileNameExt_.contains(".spc",Qt::CaseInsensitive))
            {
                if(pTree)
                {
                    pLeaf = new QTreeWidgetItem(pTree, lTemp);
                    pLeaf->setIcon(0,QIcon(":/images/spectral.png"));
                }
            }
            else if(sPathFileNameExt_.contains(".scr",Qt::CaseInsensitive))
            {
                if(pTree)
                {
                    pLeaf = new QTreeWidgetItem(pTree, lTemp);
                    pLeaf->setIcon(0,QIcon(":/images/script.png"));
                }
            }
            else if(sPathFileNameExt_.contains(".out",Qt::CaseInsensitive))
            {
                if(pTree)
                {
                    pLeaf = new QTreeWidgetItem(pTree, lTemp);
                    pLeaf->setIcon(0,QIcon(":/images/output.png"));
                }
            }
            else if(sPathFileNameExt_.contains(".mtx",Qt::CaseInsensitive))
            {
                if(pTree)
                {
                    pLeaf = new QTreeWidgetItem(pTree, lTemp);
                    pLeaf->setIcon(0,QIcon(":/images/matrix.png"));
                }
            }
        }
    }
}

bool CMainWindow::addNewProjectToTreeDock(QStringList& lPathProjectNameExts_)
{
    Q_ASSERT(!lPathProjectNameExts_.isEmpty());

    QTreeWidgetItem* pTree = NULL;
    QTreeWidgetItem* pLeaf = NULL;
    QMutableStringListIterator i(lPathProjectNameExts_);

    //check whether the project has been opened
    if(isProjectOpened(lPathProjectNameExts_.at(0))) 
    {
        QMessageBox::information(this, tr("Warning"), tr("the Project has been opened already"));
        return false;
    }

    // not opened yet then add into the tree widget
    while (i.hasNext()) {
        QString sPathFileNameExt = i.next();
        QString sFileName = QFileInfo(sPathFileNameExt).fileName();
        QStringList lTemp;lTemp.append(sFileName);lTemp.append(sPathFileNameExt);

        if(sPathFileNameExt.contains(".prj",Qt::CaseInsensitive))
        {
            pTree = new QTreeWidgetItem(_pTreeWidget, lTemp);//
            pTree->setIcon(0,QIcon((":/images/project_whole.png")));
            _pTreeWidget->expandAll();
        }
        else if(sPathFileNameExt.contains(".init",Qt::CaseInsensitive))
        {
            if(pTree)
            {
                pLeaf = new QTreeWidgetItem(pTree, lTemp);
                pLeaf->setIcon(0,QIcon(":/images/init.png"));
            }
        }
        else if(sPathFileNameExt.contains(".spc",Qt::CaseInsensitive))
        {
            if(pTree)
            {
                pLeaf = new QTreeWidgetItem(pTree, lTemp);
                pLeaf->setIcon(0,QIcon(":/images/spectral.png"));
            }
        }
        else if(sPathFileNameExt.contains(".scr",Qt::CaseInsensitive))
        {
            if(pTree)
            {
                pLeaf = new QTreeWidgetItem(pTree, lTemp);
                pLeaf->setIcon(0,QIcon(":/images/script.png"));
            }
        }
        else if(sPathFileNameExt.contains(".out",Qt::CaseInsensitive))
        {
            if(pTree)
            {
                pLeaf = new QTreeWidgetItem(pTree, lTemp);
                pLeaf->setIcon(0,QIcon(":/images/output.png"));
            }
        }
        else if(sPathFileNameExt.contains(".mtx",Qt::CaseInsensitive))
        {
            if(pTree)
            {
                pLeaf = new QTreeWidgetItem(pTree, lTemp);
                pLeaf->setIcon(0,QIcon(":/images/matrix.png"));
            }
        }
    }

    
    return true;
}


void CMainWindow::addSpreadsheet(CSpreadsheet* pSpreadsheet_)
{
    QMdiSubWindow *pSubWindow = _pMDIArea->addSubWindow(pSpreadsheet_);
    pSubWindow->show();
}

void CMainWindow::open()
{
    //CSpreadsheet* pSpreadsheet = CSpreadsheet::open(this);
    //if(pSpreadsheet) addSpreadsheet(pSpreadsheet);
    QFileDialog cFDlg;
    cFDlg.setFileMode(QFileDialog::ExistingFiles);
    QStringList lFiles = cFDlg.getOpenFileNames(this,tr("Open"),".",
        tr("(*.prj *.init *.spc *.scr *.out)\n" "project files (*.prj)\n" "init files (*.init)\n" "spectral files (*.spc)\n" "output files (*.out)\n" "All files (*.*)"));
    if(lFiles.isEmpty()) return;
    updateSubWindows(lFiles);
    openFiles(lFiles);
}

void CMainWindow::openProjectFile()
{
    QString sPathProjectNameExt = QFileDialog::getOpenFileName(this,tr("Open Project file"), ".",tr("project files (*.prj)\n" "All files (*.*)"));
    QStringList lProjectFileNames;
    // get all the files in this project
    CSpreadsheet::openFile(sPathProjectNameExt,this,&lProjectFileNames);
    if(addNewProjectToTreeDock(lProjectFileNames))
    {
        setCurrentProject(sPathProjectNameExt);
        updateSubWindows(lProjectFileNames);
        openFiles(lProjectFileNames);
    }
}
void CMainWindow::openRecentProject()
{
    QAction *action = qobject_cast<QAction *>(sender());
    if (action)
        loadProject(action->data().toString());
}

void CMainWindow::updateRecentProjectActions()
{
    QMutableStringListIterator i(_slRecentProjects);
    while (i.hasNext()) {
        if (!QFile::exists(i.next()))
            i.remove();
    }

    for (int j = 0; j < MaxRecentFiles; ++j) {
        if (j < _slRecentProjects.count()) {
            QString text = tr("&%1 %2").arg(j + 1).arg(QFileInfo(_slRecentProjects[j]).fileName());
            _aRecentFileActions[j]->setText(text);
            _aRecentFileActions[j]->setData(_slRecentProjects[j]);
            _aRecentFileActions[j]->setVisible(true);
        } else {
            _aRecentFileActions[j]->setVisible(false);
        }
    }
    _pSeparatorAct1->setVisible(!_slRecentProjects.isEmpty());
}

void CMainWindow::openFiles(const QStringList& lFileNames_)
{
    for(int i=0;i<lFileNames_.length();i++)
    {
        openFile(lFileNames_.at(i));
    }
    // title sub windows
    //_pMDIArea->tileSubWindows();
}
void CMainWindow::openFile(const QString& sFileName_)
{
    CSpreadsheet* pSpreadSheet = CSpreadsheet::openFile(sFileName_,this);
    if(pSpreadSheet) addSpreadsheet(pSpreadSheet);
    //_pMDIArea->tileSubWindows();
}

void CMainWindow::setCurrentProject(const QString &sPathFileNameExt_)
{
    _sCurPathProjectExt = sPathFileNameExt_;
    setWindowModified(false);
    QString sShownName = tr("Untitled");
    if (!_sCurPathProjectExt.isEmpty()) {
        sShownName = QFileInfo(_sCurPathProjectExt).fileName();
        _slRecentProjects.removeAll(_sCurPathProjectExt);
        _slRecentProjects.prepend(_sCurPathProjectExt);
        updateRecentProjectActions();
    }
    setWindowTitle(tr("%1 - %2").arg(sShownName).arg(tr("VPAL")));
}

bool CMainWindow::loadProject(const QString &sPathFrojectNameExt_)
{
    QStringList lProjectFileNames;
    CSpreadsheet::openFile(sPathFrojectNameExt_,this,&lProjectFileNames);
    if(addNewProjectToTreeDock(lProjectFileNames))
    {
        setCurrentProject(sPathFrojectNameExt_);
        updateSubWindows(lProjectFileNames);
        openFiles(lProjectFileNames);
        statusBar()->showMessage(tr("Project loaded"), 2000);
    }
    else
    {
        statusBar()->showMessage(tr("Loading canceled"), 2000);
    }
    return true;
}

void CMainWindow::setFullScreen( bool bFullScreen_ )
{
    if(bFullScreen_!=_bFullscreen)
    {
        _bFullscreen = bFullScreen_;
        emit fullScreenChanged(_bFullscreen);
    }
}

void CMainWindow::setDisplayMode( bool bShow_ )
{
    //if(_bShowGraphics!=bShow_)
    {
        _bShowGraphics = bShow_;
        emit displayModeChanged(_bShowGraphics);
    }
}

void CMainWindow::writeSettings()
{
    QSettings settings("Software Inc.", "Spreadsheet");

    settings.setValue("geometry", saveGeometry()); // save the main window's geometry
    settings.setValue("recentFiles",  _slRecentProjects);
    settings.setValue("fullscreen",   _bFullscreen);
    settings.setValue("showgraphics", _bShowGraphics);
    settings.setValue("currentproject", _sCurPathProjectExt);
}

void CMainWindow::readSettings()
{
    QSettings settings("Software Inc.", "Spreadsheet");

    restoreGeometry(settings.value("geometry").toByteArray());
    _slRecentProjects = settings.value("recentFiles").toStringList();
    updateRecentProjectActions();
    
    //bool bFullScreen = settings.value("fullscreen", false).toBool();
    //setFullScreen(bFullScreen);
    //bool bShowGraphics = settings.value("showgraphics", true).toBool();
    //setDisplayMode(bShowGraphics);

    _sCurPathProjectExt = settings.value("currentproject", "").toString();
}

bool CMainWindow::closeSubWindow()
{
    _pMDIArea->closeActiveSubWindow();
    return true;
}

bool CMainWindow::closeAll()
{
    _pMDIArea->closeAllSubWindows();
    return true;
}
void CMainWindow::closeEvent( QCloseEvent *pEvent_ )
{
    // close and save all sub-windows
    QList<QMdiSubWindow *> lWindows = _pMDIArea->subWindowList();
    for (int i = 0; i < lWindows.size(); ++i) {
        CSpreadsheet *pSpreadsheet = qobject_cast<CSpreadsheet *>(lWindows.at(i)->widget());
        pSpreadsheet->closeEvent(pEvent_);
    }
    // write settings 
    writeSettings();
    // close main window
    pEvent_->accept();
}

void CMainWindow::updateActions()
{
    bool bHasSpreadsheet =  (activeSpreadsheet()!=0);

    _pSaveAct->setEnabled(bHasSpreadsheet);
    _pSaveAsAct->setEnabled(bHasSpreadsheet);
    _pPasteAct->setEnabled(bHasSpreadsheet);
    _pCloseAct->setEnabled(bHasSpreadsheet);
    _pCloseAllAct->setEnabled(bHasSpreadsheet);
    _pTileAct->setEnabled(bHasSpreadsheet);
    _pCascadeAct->setEnabled(bHasSpreadsheet);
    _pNextAct->setEnabled(bHasSpreadsheet);
    _pPreviousAct->setEnabled(bHasSpreadsheet);
    _pSeparatorAct2->setVisible(bHasSpreadsheet);
    _pSelectAllAct->setEnabled(bHasSpreadsheet);
    _pSelectRowAct->setEnabled(bHasSpreadsheet);
    _pSelectColumnAct->setEnabled(bHasSpreadsheet);
    _pSelectSubMenu->setEnabled(bHasSpreadsheet);
    _pFindAct->setEnabled(bHasSpreadsheet);
    _pGotoCellAct->setEnabled(bHasSpreadsheet);
    _pExportAct->setEnabled(bHasSpreadsheet);
    _pSortAct->setEnabled(bHasSpreadsheet);

    if(_pMDIArea->subWindowList().isEmpty())
    {    
        _pRunAct->setEnabled(false);
        _pNextTrialAct->setEnabled(false);
        _pStopExperimentAct->setEnabled(false);
    }
    else
    {
        _pRunAct->setEnabled(true);
        _pNextTrialAct->setEnabled(true);
        _pStopExperimentAct->setEnabled(true);
    }
    //_pSortAct->setEnabled(bHasSpreadsheet);
    //_pRecalculateAct->setEnabled(bHasSpreadsheet);
    //_pShowGridAction->setEnabled(bHasSpreadsheet);
    //_pAutoRecalculateAction->setEnabled(bHasSpreadsheet);

    bool bHasSelection = activeSpreadsheet() && !(activeSpreadsheet()->selectedRanges()).isEmpty();
    _pCopyAct->setEnabled(bHasSelection);
    _pCutAct->setEnabled(bHasSelection);
    _pDeleteAct->setEnabled(bHasSelection);
    _pInsertAct->setEnabled(bHasSelection);
}

CSpreadsheet* CMainWindow::activeSpreadsheet()
{
    QMdiSubWindow *pSubWindow = _pMDIArea->activeSubWindow();
    if(pSubWindow)
        return qobject_cast<CSpreadsheet*>(pSubWindow->widget());
    return 0;
}

void CMainWindow::updateWindowMenu()
{
    _pWindowMenu->clear();
    _pWindowMenu->addAction(_pCloseAct);
    _pWindowMenu->addAction(_pCloseAllAct);
    _pWindowMenu->addSeparator();
    _pWindowMenu->addAction(_pTileAct);
    _pWindowMenu->addAction(_pCascadeAct);
    _pWindowMenu->addSeparator();
    _pWindowMenu->addAction(_pNextAct);
    _pWindowMenu->addAction(_pPreviousAct);
    _pWindowMenu->addAction(_pSeparatorAct2);

    QList<QMdiSubWindow *> lWindows = _pMDIArea->subWindowList();
    _pSeparatorAct2->setVisible(!lWindows.isEmpty());

    for (int i = 0; i < lWindows.size(); ++i) {
        CSpreadsheet *pSpreadsheet = qobject_cast<CSpreadsheet *>(lWindows.at(i)->widget());

        QString sText;
        if (i < 9) {
            sText = tr("&%1 %2").arg(i + 1).arg(QFileInfo(pSpreadsheet->getCurrentFile()).fileName());
        } else {
            sText = tr("%1 %2") .arg(i + 1).arg(QFileInfo(pSpreadsheet->getCurrentFile()).fileName());
        }
        QAction *pAct = _pWindowMenu->addAction(sText);
        pAct->setCheckable(true);
        pAct->setChecked(pSpreadsheet == activeSpreadsheet());
        connect(pAct, SIGNAL(triggered()), _pWindowMapper, SLOT(map()));
        _pWindowMapper->setMapping(pAct, lWindows.at(i));
    }
}

void CMainWindow::setActiveSubWindow(QWidget *pWindow_)
{
    if (!pWindow_)
        return;
    QMdiSubWindow* pSubW = qobject_cast<QMdiSubWindow *>(pWindow_);
    _pMDIArea->setActiveSubWindow(pSubW);

}

void CMainWindow::setMaximizeSubWindow(QTreeWidgetItem* pTree_)
{
    setActiveSubWindow(pTree_);
    QMdiSubWindow* pSubW = _pMDIArea->activeSubWindow();
    pSubW->setWindowState(Qt::WindowMaximized);
}

void CMainWindow::setActiveSubWindow(QTreeWidgetItem* pTree_)
{
    // close and save all sub-windows
    QList<QMdiSubWindow *> lWindows = _pMDIArea->subWindowList();
    for (int i = 0; i < lWindows.size(); ++i) {
        CSpreadsheet *pSpreadsheet = qobject_cast<CSpreadsheet *>(lWindows.at(i)->widget());
        if(pSpreadsheet->getCurrentFile()==pTree_->data(1,0).toString())
        {
            _pMDIArea->setActiveSubWindow(lWindows.at(i));  
            return;
        }
    }
    openFile(pTree_->data(1,0).toString());
    return;
}

void CMainWindow::cut()
{
    if (activeSpreadsheet())
        activeSpreadsheet()->cut();
}

void CMainWindow::cutCurrentRow()
{
    if (activeSpreadsheet())
        activeSpreadsheet()->cutCurrentRow();
}

void CMainWindow::copy()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->copy();
}

void CMainWindow::paste()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->paste();
}

void CMainWindow::del()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->del();
}

void CMainWindow::insertRowAboveCurrent()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->insertRowAboveCurrent();
}
void CMainWindow::selectCurrentRow()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->selectCurrentRow();
}

void CMainWindow::selectCurrentColumn()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->selectCurrentColumn();
}

void CMainWindow::selectAll()
{
    if(activeSpreadsheet())
        activeSpreadsheet()->selectAll();
}



//void CMainWindow::setStatusBar(QMdiSubWindow* pSubWindow_)
//{
//    if(!pSubWindow_) return;
//    CSpreadsheet* pSpreadSheet = qobject_cast<CSpreadsheet*>(pSubWindow_->widget());
//        //connect(pSpreadSheet, SIGNAL(modified()),                          this, SLOT(spreadsheetModified()));
//
//    //updateStatusBar();
//}

void CMainWindow::updateStatusBar()
{
    if(activeSpreadsheet())
    {
        _pLocationLabel->setText(activeSpreadsheet()->currentLocation());
        _pFormulaLabel->setText(activeSpreadsheet()->currentFormula());
    }
}

void CMainWindow::spreadsheetModified()
{
    setWindowModified(true);
    updateStatusBar();
}

void CMainWindow::timerEvent( QTimerEvent * e )
{
    if (e->timerId() == _nTimerID) {
        updateStatusBar();
    } else {
        QWidget::timerEvent(e);
    }
}

void CMainWindow::runExperiment()
{
    try
    {
        //1) load data from input files.
        loadData();//load data from spreadsheets
        //2) initialize graphics engine.
        _pGlWidget->setDataPtr(_pData); //set the pointer of data class to graphics engine.
        _pGlWidget->init(); //init graphics engine. 
        //3) set up the display environment.
        setDisplayMode(false);//first switch off the graphical mode
        setDisplayMode(true); //then switch on the graphical mode 
        showFullScreen(true); //set the full screen mode.
    }
    catch(exception& e)
    {
        QMessageBox::warning(this,QString("Error"),QString(e.what()),QMessageBox::Yes); 
        //if(_pData)
        //    _pData->disConnectFlyBox();
    }
    return;
}

void CMainWindow::nextTrial()
{
    if(_pData&&_pGlWidget)
        _pGlWidget->next();
}

void CMainWindow::exitAllTrial()
{
    if(_pData&&_pGlWidget)
    {
        _pGlWidget->exit();
        //_pData->disConnectFlyBox();
    }

    setDisplayMode(false);
    
}

void CMainWindow::loadData()
{
    saveAll();//save all the spreadsheet in the projects

    QStringList lPathFileNameExts = getFileNames(_sCurPathProjectExt); // the current project name
    vector<CSpreadsheet*> vSpreadsheets;
    int i;
    for(i=0;i<lPathFileNameExts.length();i++)
    {
        CSpreadsheet* pSpr = CSpreadsheet::openFile(lPathFileNameExts.at(i),NULL);
        vSpreadsheets.push_back(pSpr);
    }
    for(i=0;i<(int)vSpreadsheets.size();i++)
    {
        if(vSpreadsheets[i]->currentFile().contains("Room.init"))
        {    
            if(_pData) delete _pData;
            _pData = NULL;
            _pData = new CRoomData;
            break;
        }
    }
    if(i==lPathFileNameExts.length())
        throw exception("Unrecognized project.");

    _pData->setTimeIdx() = 0;
    _pData->setTrialIdx() = 0;

    if(_pData)  _pData->load(vSpreadsheets);
  
    return;
}

QStringList CMainWindow::getFileNames(QString& sPathProjectExt_)
{
    QStringList lFiles;
    for(int i=0;i<_pTreeWidget->topLevelItemCount();i++)
    {
        // check root
        QTreeWidgetItem* pTree = _pTreeWidget->topLevelItem(i);
        if(pTree->data(1,0).toString()==sPathProjectExt_)
        {
            // check children
            for(int j=0;j<pTree->childCount();j++)
            {
                QTreeWidgetItem* pChild = pTree->child(j);
                lFiles.append(pChild->data(1,0).toString());
            }
        }
    }
    if (lFiles.isEmpty())
    {
        QMessageBox::information(this, tr("Information"), tr("no project has been opened"));
    }
    return lFiles;
}

void CMainWindow::exportData()
{
    CSpreadsheet* pSpreadsheet = new CSpreadsheet(this);
    QString sPapthFileNameExt=QFileInfo(_sCurPathProjectExt).path()+"/"+QFileInfo(_sCurPathProjectExt).baseName()+".out";
    pSpreadsheet->createFile(sPapthFileNameExt);
    addSpreadsheet(pSpreadsheet);
    addNewFileToCurrentProject(sPapthFileNameExt);
}

void CMainWindow::find()
{
    if (!_pFindDialog) {
        _pFindDialog = new CFindDialog(this);
        connect(_pFindDialog, SIGNAL(findNext(const QString &,Qt::CaseSensitivity)),    this, SLOT(findNext(const QString &,Qt::CaseSensitivity)));
        connect(_pFindDialog, SIGNAL(findPrevious(const QString &,Qt::CaseSensitivity)),this, SLOT(findPrevious(const QString &,Qt::CaseSensitivity)));
    }

    if (_pFindDialog->isHidden()) {
        _pFindDialog->show();
    }
    else {
        _pFindDialog->raise();
        _pFindDialog->activateWindow();
    }
}

void CMainWindow::findNext(const QString &sStr_, Qt::CaseSensitivity eCs_)
{
    if (activeSpreadsheet() && activeSpreadsheet()->findNext(sStr_,eCs_))
        statusBar()->showMessage(tr("Item find."), 2000);
    else
        statusBar()->showMessage(tr("Item cannot be found."), 2000);
}

void CMainWindow::findPrevious(const QString &sStr_, Qt::CaseSensitivity eCs_)
{
    if (activeSpreadsheet() && activeSpreadsheet()->findPrevious(sStr_,eCs_))
        statusBar()->showMessage(tr("Item find."), 2000);
    else
        statusBar()->showMessage(tr("Item cannot be found."), 2000);
}

void CMainWindow::sort()
{
    if (activeSpreadsheet())
    {
        activeSpreadsheet()->sortBySelectedColumn();
    }
}

void CMainWindow::switchProject(QTreeWidgetItem* pTree_)
{
    QString sPathProjectNameExt=pTree_->data(1,0).toString();
    if(sPathProjectNameExt.contains(".prj"))
        setCurrentProject(sPathProjectNameExt);   
    return ;
}

void CMainWindow::calibration()
{
    int temp =0;
    temp++;

    try
    {
        if(_pData) delete _pData;
        _pData = new CCalibrationData;
        _pGlWidget->setDataPtr(_pData);
        _pGlWidget->init();
        //set display environment
        setDisplayMode(false);
        setDisplayMode(true);
        showFullScreen(true);
    }
    catch(exception& e)
    {
        {
            QMessageBox::warning(this,QString("Error"),QString(e.what()),QMessageBox::Yes); 
        }
    }
    return;
}